using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.ComponentModel;
namespace Jasongozy.Alaton {
    public static class Converters {
        public static T ConvertType<T>(object toConvertObject) {
            return ConvertType<T>(toConvertObject, default(T));
        }
        public static T ConvertType<T>(object toConvertObject, T defaultValue) {
            Type enumType = typeof(T);
            if (enumType.IsValueType) {
                return ParseStringToValueType<T>(toConvertObject.ToString(), defaultValue);
            }

            if ((Convert.IsDBNull(toConvertObject) || (toConvertObject == null)) || (toConvertObject.ToString() == "")) {
                if (typeof(T) == typeof(string)) {
                    defaultValue = (T)Convert.ChangeType(string.Empty, typeof(T));
                    return defaultValue;
                }
                defaultValue = default(T);
                return defaultValue;
            }
            if (enumType.IsEnum) {
                toConvertObject = Convert.ChangeType(toConvertObject, Enum.GetUnderlyingType(enumType));
                return (T)toConvertObject;
            }
            if (enumType.IsGenericType && (enumType.GetGenericTypeDefinition() == typeof(Nullable<>))) {
                NullableConverter converter = new NullableConverter(enumType);
                enumType = converter.UnderlyingType;
            }
            return (T)Convert.ChangeType(toConvertObject, enumType);

        }

        public static T ParseStringToValueType<T>(string input,T defaultValue) {
            Type disType = typeof(T);
            T res = defaultValue;
            if (disType.IsValueType) {
                MethodInfo m = disType.GetMethod("Parse", new Type[] { typeof(string) });
                try {
                    res = (T)m.Invoke(null, new object[] { input });
                } catch {}
                
            }
            return res;
        }
    }
}
